<template>
  <div class="menu-index">
    <a-card>
      <InputGroup @search="Search" @reset="Reset">
        <a-form
          :model="formData"
          :wrapper-col="{ style: { width: '150px' } }"
          layout="inline"
        >
          <a-form-item label="搜索">
            <a-input v-model:value="formData.menuName" allow-clear></a-input>
          </a-form-item>
          <a-form-item label="状态">
            <a-select ref="select" v-model:value="formData.isShow">
              <a-select-option value="">全部</a-select-option>
              <a-select-option :value="1">正常</a-select-option>
              <a-select-option :value="0">停用</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </InputGroup>

      <a-flex justify="flex-end" style="margin-bottom: 16px">
        <a-space>
          <a-button
            v-has-perm="['system:menu:save']"
            type="primary"
            @click="AddRoot"
          >
            <icon type="PlusOutlined" />
            新增
          </a-button>
        </a-space>
      </a-flex>

      <Table
        ref="table"
        :config="tableConfig"
        @view="View"
        @add="AddMenu"
        @edit="Edit"
        @delete="Delete"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.title === '类型'">
            <a-tag
              v-if="record.menuType === 'M'"
              color="#2db7f5"
              ::bordered="false"
              >目录</a-tag
            >
            <a-tag
              v-else-if="record.menuType === 'C'"
              color="#87d068"
              :bordered="false"
              >菜单</a-tag
            >
            <a-tag
              v-else-if="record.menuType === 'F'"
              color="#FF8000"
              :bordered="false"
              >按钮</a-tag
            >
          </template>
          <template v-else-if="column.title === '图标'">
            <icon :type="record.icon" style="font-size: 18px" />
          </template>
          <template v-else-if="column.title === '状态'">
            <a-switch
              v-model:checked="record.isShow"
              :checkedValue="1"
              :unCheckedValue="0"
              @change="Switch(record)"
            />
          </template>
        </template>
      </Table>

      <Dialog :config="dialogConfig" @submit="Submit" @cancel="Cancel">
        <a-spin :spinning="dialogLoading">
          <a-form
            :model="dialogData"
            :disabled="dialogFormDisabled"
            :labelCol="{ span: 4 }"
            :wrapperCol="{ span: 20 }"
          >
            <a-form-item
              :label="
                dialogData.menuType == 'M'
                  ? '目录名称'
                  : dialogData.menuType == 'C'
                    ? '菜单名称'
                    : '按钮名称'
              "
              name="menuName"
            >
              <a-input v-model:value="dialogData.menuName" />
            </a-form-item>
            <a-form-item label="菜单类型" name="menuType">
              <a-radio-group v-model:value="dialogData.menuType">
                <a-radio value="M">目录</a-radio>
                <a-radio value="C">菜单</a-radio>
                <a-radio value="F">按钮</a-radio>
              </a-radio-group>
              <!--              <a-select v-model:value="dialogData.menuType">-->
              <!--                <a-select-option value="M">目录</a-select-option>-->
              <!--                <a-select-option value="C">菜单</a-select-option>-->
              <!--                <a-select-option value="F">按钮</a-select-option>-->
              <!--              </a-select>-->
            </a-form-item>
            <a-form-item
              v-if="dialogData.menuType == 'C' || dialogData.menuType == 'F'"
              label="权限标识"
              name="perms"
            >
              <a-input v-model:value="dialogData.perms" />
            </a-form-item>
            <a-form-item
              v-if="dialogData.menuType == 'C'"
              label="路径"
              name="path"
            >
              <a-input v-model:value="dialogData.path" />
            </a-form-item>
            <a-form-item
              v-if="dialogData.menuType == 'C'"
              label="组件"
              name="component"
            >
              <a-input v-model:value="dialogData.component" />
            </a-form-item>
            <a-form-item
              v-if="dialogData.menuType !== 'F'"
              label="图标"
              name="icon"
            >
              <a-popover trigger="focus" placement="bottom">
                <template #content>
                  <IconSelect @select="getIcon" />
                </template>
                <a-input v-model:value="dialogData.icon">
                  <template #prefix>
                    <icon :type="dialogData.icon" style="font-size: 14px" />
                  </template>
                </a-input>
              </a-popover>
            </a-form-item>
            <a-form-item
              v-if="dialogData.menuType !== 'F'"
              label="排序"
              name="orderNum"
            >
              <a-input-number v-model:value="dialogData.orderNum" />
            </a-form-item>
            <a-form-item label="状态" name="isShow">
              <a-switch
                v-model:checked="dialogData.isShow"
                :checkedValue="1"
                :unCheckedValue="0"
              />
            </a-form-item>
            <a-form-item
              v-if="dialogData.menuType !== 'F'"
              label="描述"
              name="description"
            >
              <a-textarea v-model:value="dialogData.description" />
            </a-form-item>
          </a-form>
        </a-spin>
      </Dialog>
    </a-card>
  </div>
</template>

<script setup>
import {
  menusTree,
  menuChangeShow,
  menuInfoById,
  menuAdd,
  menuEdit,
  menuDelete,
} from "@api/system/menu.js";
import InputGroup from "@components/InputGroup/index.vue";
import Table from "@components/Table/index.vue";
import Dialog from "@components/Dialog/index.vue";
import IconSelect from "@components/IconSelect/index.vue";
import icon from "@utils/icon";
import { ref, createVNode } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { message, Modal } from "ant-design-vue";

// 表单是否禁用
const dialogFormDisabled = ref(true);
// 弹窗加载数据loading
const dialogLoading = ref(false);
// 是否编辑
const isEdit = ref(false);
// 表格实例
const table = ref(null);
// 搜索数据
const formData = ref({
  menuName: "",
  isShow: "",
});
// 弹窗数据
let dialogData = ref({
  path: "",
  menuName: "",
  menuType: "",
  component: "",
  perms: "",
  icon: "",
  description: "",
  orderNum: 0,
  isShow: 0,
});

// 表格配置
const tableConfig = reactive({
  url: menusTree,
  columns: [
    {
      key: "menuName",
      title: "菜单名称",
      dataIndex: "menuName",
    },
    {
      key: "icon",
      title: "图标",
      dataIndex: "icon",
      align: "center",
      width: 80,
    },
    {
      title: "排序",
      dataIndex: "orderNum",
      align: "center",
      width: 80,
    },
    {
      key: "perms",
      title: "权限标识",
      align: "center",
      dataIndex: "perms",
      width: 150,
    },
    {
      key: "path",
      title: "路径",
      align: "center",
      dataIndex: "path",
      width: 200,
    },
    {
      key: "menuType",
      title: "类型",
      align: "center",
      dataIndex: "menuType",
    },

    {
      title: "状态",
      align: "center",
      dataIndex: "isShow",
    },
    {
      title: "操作",
      align: "center",
      width: 200,
    },
  ],
  params: {},
  table: {
    size: "middle",
    indentSize: 30,
    bordered: true,
    rowKey: "id",
  },
  isPagination: false,
  buttons: {
    view: "view",
    edit: ["system:menu:update"],
    add: ["system:menu:save"],
    delete: ["system:menu:delete"],
    role: ["system:menu:role"],
  },
  // buttons: ["view", "add", "edit", "delete"],
});

// 新增、查看、修改弹窗配置
const dialogConfig = reactive({
  open: false,
  width: "40%",
  okText: "确定",
  cancelText: "取消",
  subLoading: false,
  destroyOnClose: true,
});

// const buttonGroupConfig = reactive([
//   {
//     label: "新增",
//     type: "primary",
//     icon: "PlusOutlined",
//     emitCode: "add",
//   },
//
//   {
//     label: "",
//     type: "default",
//     shape: "circle",
//     icon: "ExportOutlined",
//     emitCode: "export",
//   },
// ]);

const Search = () => {
  tableConfig.params = formData.value;
  table.value.loadData();
};
const Reset = () => {
  formData.value = {};
  tableConfig.params = formData.value;
  table.value.loadData();
};

// 表格查看、新增、编辑、删除
const View = async (record) => {
  dialogLoading.value = true;
  dialogConfig.open = true;
  dialogConfig.title = "查看";
  dialogFormDisabled.value = true;
  const response = await menuInfoById(record.id);
  if (response.code === 200) {
    dialogData.value = response.data;
  } else {
    message.error("获取菜单信息失败，" + response.message);
  }
  dialogLoading.value = false;
};
// 添加根目录或一级菜单
const AddRoot = () => {
  isEdit.value = false;
  dialogConfig.open = true;
  dialogFormDisabled.value = false;
  dialogConfig.title = "新增";
};
// 添加该项的子菜单
const AddMenu = async (record) => {
  isEdit.value = false;
  dialogConfig.open = true;
  dialogConfig.title = "新增";
  dialogFormDisabled.value = false;
  dialogData.value.pid = record.id;
};

const Edit = async (record) => {
  dialogLoading.value = true;
  isEdit.value = true;
  dialogConfig.open = true;
  dialogConfig.title = "编辑";
  dialogFormDisabled.value = false;
  const response = await menuInfoById(record.id);
  if (response.code === 200) {
    dialogData.value = response.data;
  } else {
    message.error("获取菜单信息失败，" + response.message);
  }
  dialogLoading.value = false;
};
const Delete = (record) => {
  // 弹窗确认删除
  Modal.confirm({
    title: "",
    icon: createVNode(ExclamationCircleOutlined),
    content: "是否确认删除？",
    centered: true,
    async onOk() {
      try {
        const response = await menuDelete([record.id]);
        if (response.code === 200) {
          message.success("删除成功！");
          table.value.loadData();
        } else {
          message.error("删除失败，" + response.message);
        }
      } catch {
        return console.log("errors!");
      }
    },
    onCancel() {},
  });
};
// 状态切换
const Switch = async (record) => {
  const response = await menuChangeShow({
    id: record.id,
  });
  if (response.code === 200) {
    message.success("修改状态成功！");
    table.value.loadData();
  } else {
    message.error("修改状态失败，" + response.message);
    table.value.loadData();
  }
};

// 弹窗表单提交
const Submit = async () => {
  dialogConfig.subLoading = true;
  try {
    const response = isEdit.value
      ? await menuEdit({ ...dialogData.value })
      : await menuAdd({ ...dialogData.value });
    if (response.code === 200) {
      message.success(isEdit.value ? "修改成功！" : "添加成功！");
      dialogConfig.open = false;
      dialogData.value = {};
      table.value.loadData();
    } else {
      message.error(
        (isEdit.value ? "修改失败，" : "添加失败，") + response.message,
      );
    }
  } catch (error) {
    message.error("操作失败，请稍后重试。");
  } finally {
    dialogConfig.subLoading = false;
  }
};
// 弹窗表单取消
const Cancel = () => {
  dialogConfig.open = false;
  dialogData.value = {};
};

const getIcon = (icon) => {
  debugger;
  console.log(icon);
  dialogData.value.icon = icon;
};
</script>

<style scoped lang="scss"></style>
